package com.ocom.aiot.controller;

import com.github.pagehelper.PageInfo;
import com.ocom.aiot.service.OtaPushInfoService;
import com.ocom.aiot.service.OtaVerInfoService;
import com.ocom.common.constant.AiotUrl;
import com.ocom.common.entity.aiot.EntityOtaVerInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.aiot.OtaPushVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/8/24
 **/
@Slf4j
@RestController
public class OtaController {

	@Autowired
	OtaPushInfoService otaPushInfoService;

	@Autowired
	private OtaVerInfoService otaVerInfoService;


	@PostMapping(AiotUrl.URLP_AIOT_getOtaList)
	public Result getList(Integer page, Integer size,@RequestParam(required = false) String deviceNo) {
		return ResultUtil.success(otaPushInfoService.getOtaList(page,size,deviceNo));
	}


	@PostMapping(AiotUrl.URLP_AIOT_getOtaDeviceFlag)
	public Result getOtaUpdate(String deviceNo, String appVer) {
		EntityOtaVerInfo entityXfAppVerInfo = otaPushInfoService.getOtaPush(deviceNo,appVer);
		if(entityXfAppVerInfo == null) 	return ResultUtil.error(ResultEnum.Err_3064);
		return ResultUtil.success(entityXfAppVerInfo);
	}

	@PostMapping(AiotUrl.URLP_AIOT_otaPush)
	public Result otaPush(@RequestBody OtaPushVo otaPushVo) {
		otaPushInfoService.pushVer(otaPushVo);
		return ResultUtil.success();
	}

	//5.1.添加ota文件(saveOtaFile)
	@PostMapping(AiotUrl.Url_Aiot_saveOtaFile)
	public Result saveOtaFile(String appVer,String url,Integer type) {
		int i=otaVerInfoService.saveOtaFile(appVer,url,type);
		if (i>0){
			return ResultUtil.success();
		}else {
			return ResultUtil.error(ResultEnum.Err_3014);
		}
	}

	//获取ota文件列表（otaFileList）
	@PostMapping(AiotUrl.Url_Aiot_otaFileList)
	public Result otaFileList(Integer page,Integer size) {
		Map<String, Object> map = new HashMap<>();
		try {
			List<EntityOtaVerInfo>  list=otaVerInfoService.otaFileList(page,size);
			PageInfo<EntityOtaVerInfo> entityAppVerInfoPageInfo = new PageInfo<>(list);
			map.put("total",entityAppVerInfoPageInfo.getTotal());
			map.put("list", list);
		}catch (Exception exception){
			log.error("获取ota文件列表："+exception.getMessage());
			return ResultUtil.error(ResultEnum.Err_2009);
		}

		return ResultUtil.success(map);
	}
}
